package com.bupt.ilink.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bupt.ilink.entity.Studyspace.tree.JsonEntity;
import com.bupt.ilink.entity.Studyspace.tree.JsonTagEntity;
import com.bupt.ilink.entity.Studyspace.tree.StudyTreeJsonNodeStatus;
import com.bupt.ilink.entity.Studyspace.tree.TagEntity;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.mapper.StudyTreeJsonMapper;
import com.bupt.ilink.mapper.StudyTreeJsonNodeStatusMapper;
import com.bupt.ilink.mapper.StudyTreeJsonTagMapper;
import com.bupt.ilink.mapper.StudyTreeTagMapper;
import com.bupt.ilink.request.Study.UpdateJsonStatusRequest;
import com.bupt.ilink.service.StudyTreeJsonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class StudyTreeJsonServiceImpl implements StudyTreeJsonService {

    @Autowired
    private StudyTreeJsonMapper studyTreeJsonMapper;

    @Autowired
    private StudyTreeTagMapper studyTreeTagMapper;

    @Autowired
    private StudyTreeJsonTagMapper studyTreeJsonTagMapper;

    @Autowired
    private StudyTreeJsonNodeStatusMapper studyTreeJsonNodeStatusMapper;

    @Override
    public List<String> getAllTags() {
        return studyTreeTagMapper.getAllTags();
    }

    @Override
    public List<TagEntity> getCommonTags() { return studyTreeTagMapper.getCommonTags(); }

    @Override
    public List<JsonEntity> getJsonsByTagsAndPagination(List<String> tagNames,String keyword, int page, int size) {
        QueryWrapper<JsonEntity> queryWrapper = new QueryWrapper<>();

        // 如果tagNames不为空且不为空列表，则进行标签筛选
        if (tagNames != null && !tagNames.isEmpty()) {
            // 先根据tagName获取对应的tagId列表
            List<Long> tagIds = studyTreeTagMapper.selectList(
                    new QueryWrapper<TagEntity>().in("tag_name", tagNames)
            ).stream().map(TagEntity::getTagId).collect(Collectors.toList());

            // 如果没有找到任何tagId，直接返回空列表
            if (tagIds.isEmpty()) {
                return Collections.emptyList();
            }

            // 根据获取到的tagId，在jsonTag表中查找对应的jsonId
            List<Long> jsonIds = studyTreeJsonTagMapper.selectList(
                    new QueryWrapper<JsonTagEntity>().in("tag_id", tagIds)
            ).stream().map(JsonTagEntity::getJsonId).collect(Collectors.toList());

            // 如果筛选出的jsonIds为空，直接返回空列表
            if (jsonIds.isEmpty()) {
                return Collections.emptyList();
            }

            // 根据json_id列表添加查询条件
            queryWrapper.in("id", jsonIds);
        }

        // 如果关键词不为空，则在 name, description, jsonContent 中查找
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper ->
                    wrapper.like("name", keyword)
                            .or().like("description", keyword)
                            .or().like("json_content", keyword)
            );
        }

        // 创建分页请求
        Page<JsonEntity> pageRequest = new Page<>(page, size);

        // 执行分页查询
        return studyTreeJsonMapper.selectPage(pageRequest, queryWrapper).getRecords();
    }

    @Override
    public JsonEntity getJsonById(Long id) {
        JsonEntity jsonEntity=studyTreeJsonMapper.selectById(id);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user =  (User) authentication.getPrincipal();
        String userId= user.getUserId();
        String jsonStatus=studyTreeJsonNodeStatusMapper.findJsonStatusByUserIdAndJsonId(userId, id);
        System.out.println(jsonStatus);
        if (jsonStatus != null) {
            jsonEntity.setJsonContent(jsonStatus); // 设置新的jsonContent
        }
        return jsonEntity;
    }

    @Override
    public void saveJsonEntity(JsonEntity jsonEntity) {
        studyTreeJsonMapper.insert(jsonEntity);
    }

    @Override
    public TagEntity getOrCreateTag(String tagName) {
        // Try to find an existing tag
        QueryWrapper<TagEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tag_name", tagName);
        TagEntity tagEntity = studyTreeTagMapper.selectOne(queryWrapper);

        // If not found, create a new tag
        if (tagEntity == null) {
            tagEntity = new TagEntity();
            tagEntity.setTagName(tagName);
            studyTreeTagMapper.insert(tagEntity);
        }

        return tagEntity;
    }
    @Override
    public void saveJsonTagEntity(JsonTagEntity jsonTagEntity) {
        studyTreeJsonTagMapper.insert(jsonTagEntity);
    }



    /**
     * 为特定用户存储所有 JSON 的副本
     * @param userId 用户的ID
     */
    @Override
    public void storeJsonCopiesForUser(String userId) {
        // 获取所有的JsonEntity
        List<JsonEntity> jsonEntityList = studyTreeJsonMapper.selectList(null);

        // 遍历所有的JsonEntity，并为当前用户存储副本
        for (JsonEntity jsonEntity : jsonEntityList) {
            StudyTreeJsonNodeStatus nodeStatus = new StudyTreeJsonNodeStatus();
            nodeStatus.setId(UUID.randomUUID().toString()); // 生成随机 ID
            nodeStatus.setUserId(userId); // 设置用户ID
            nodeStatus.setJsonId(jsonEntity.getId()); // 使用JsonEntity的ID
            nodeStatus.setJsonStatus(jsonEntity.getJsonContent()); // 使用JsonEntity的jsonContent作为jsonStatus
            // 将数据插入到数据库
            studyTreeJsonNodeStatusMapper.insert(nodeStatus);
        }
    }
    /**
     * 根据 userId 和 jsonId 更新 jsonStatus
     */
    @Transactional
    @Override
    public void updateJsonStatus(UpdateJsonStatusRequest updateJsonStatusRequest) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user =  (User) authentication.getPrincipal();
        String userId= user.getUserId();
        Long jsonId=updateJsonStatusRequest.getJsonId();
        String jsonStatus=updateJsonStatusRequest.getJsonStatus();
        studyTreeJsonNodeStatusMapper.updateJsonStatus(userId, jsonId, jsonStatus);
    }
}
